import Encryption_and_decryption as ed
import base64
import json

# 编码为base64 URL安全格式
def base64url_encode(data):
    encoded_bytes = base64.urlsafe_b64encode(data)
    encoded_text = encoded_bytes.decode('utf-8').rstrip('=')
    return encoded_text

# 解码base64 URL安全格式
def base64url_decode(encoded_text):
    padding = len(encoded_text) % 4
    encoded_text += '=' * (4 - padding)
    decoded_bytes = base64.urlsafe_b64decode(encoded_text.encode('utf-8'))
    return decoded_bytes

# 将 JSON 对象的所有字符串值处理为连续字符串，并使用空格分隔
def flatten_json(json_obj):
    flattened = []

    def flatten(obj):
        if isinstance(obj, dict):
            for value in obj.values():
                flatten(value)
        elif isinstance(obj, list):
            for item in obj:
                flatten(item)
        elif isinstance(obj, str):
            flattened.append(obj)
    
    flatten(json_obj)
    return ' '.join(flattened)

# payload: share_id + file_id + date_limit 
# url : payload.public_key.token
def jwt_generate(payload,tmp):
    # 由空格分割的公开信息字符串
    payload_str = flatten_json(payload)
    # 用户公钥_用户签名
    p_t = ed.token_generate( payload['file_id'],payload['date_limit'],
        payload['share_id'],tmp['hash_password'],tmp['user_salt'])

    payload_str = base64url_encode(payload_str.encode('utf-8'))
    public_key = base64url_encode(p_t[0])
    token = base64url_encode(p_t[1])

    return payload_str + '.' + public_key + '.' + token

def jwt_to_json(jwt):

    first_dot = jwt.index('.')
    last_dot = jwt.rindex('.')

    payload = base64url_decode(jwt[:first_dot]).decode('utf-8')
    public_key = base64url_decode(jwt[first_dot + 1:last_dot])
    token = base64url_decode(jwt[last_dot + 1:])

    payload_list = payload.split()

    share_id = payload_list[0]
    file_id = payload_list[1]
    date_limit = payload_list[2]

    if ed.token_verify(file_id,date_limit,share_id,token,public_key):

        jwt_json = {
            "share_id":share_id,
            "file_id":file_id,
            "date_limit":date_limit
        }
        
        return jwt_json

    else :

        return False